package Hxw3DEngine.asset.loader
{
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.utils.ByteArray;
	import flash.system.LoaderContext;
	import flash.system.ApplicationDomain;
	import Hxw3DEngine.asset.AssetManage;
	import org.osflash.async.Deferred;
	
	public class LoaderDeferred extends Deferred
	{
		
		private var _url:String;
		private var _data:*;
		
		public function LoaderDeferred(url:String, bytes:ByteArray = null)
		{
			_url = url;
			
			if(bytes == null){
				try
				{
					AssetManage.load(url, onUrlLoadComplate);
				}
				catch (e:Error)
				{
					reject(e);
				}
			}else {
				var loader:Loader = new Loader();
				loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onBytesLoadComplete);
				loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onBytesError);
				var context:LoaderContext = new LoaderContext(false, ApplicationDomain.currentDomain);
				loader.loadBytes(bytes, context);
			}
		}
		
		private function onUrlLoadComplate():void
		{
			_data = AssetManage.getAsset(_url);
			resolve(this);
		}
		
		private function onBytesLoadComplete(e:Event):void
		{
			if (e.target is Loader)
			{
				_data = e.target.data;
			}
			else if (e.target is LoaderInfo)
			{
				_data = e.target.content.bitmapData;
			}
			resolve(this);
		}
		private function onBytesError(e:IOErrorEvent):void
		{
			reject(new Error(e.text,e.errorID));
		}
		
		public function get url():String 
		{
			return _url;
		}
		
		public function get data():* 
		{
			return _data;
		}
	}
}
